package org.gitos.cloud.comet.tcp;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.gitos.cloud.domain.comm.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * ChildChannelInit
 * netty初始化设置数据处理handler
 *
 * @author purely
 * @date 2015/12/4
 */
@Component
public class ChildChannelInit extends ChannelInitializer {
    @Value("${" + Constant.IDLE_READ + "}")
    private String idleRead;
    @Autowired
    private HeartBeatHandler heartBeatHandler;

    @Autowired
    private DispatchBucketHandler dispatchBucketHandler;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pip = channel.pipeline();
        pip.addLast("LoggingHandler", new LoggingHandler(LogLevel.INFO));
        pip.addLast("registCtxHandler", new RegistCtxHandler());
        pip.addLast("IdleStateHandler", new IdleStateHandler(Integer.valueOf(idleRead), 0, 0));
        pip.addLast("HeartBeatHandler", heartBeatHandler);
        //有包头的解析数据包
        //pip.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(65539, 2, 2));
        //没有包头的解析数据包
        pip.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(65539, 0, 2, -2, 0));
        pip.addLast("TcpDecoder", new TcpDecoder());
        pip.addLast("DispatchBucketHandler", dispatchBucketHandler);
        pip.addLast("TcpEncoder", new TcpEncoder());
    }
}
